<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>gitlab-cicd | mozihao</title><meta name="keywords" content="mozihao github"><meta name="author" content="mozihao"><meta name="copyright" content="mozihao"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="使用docker + gitlab自动化部署前端项目安装docker和gitlab-ce及配置 运行linux服务器，终端打开 1ssh root@ + 公网ip  公网ip：阿里云云服务器–&gt;实例与镜像–&gt;实例（实例详情中的公网ip）  linux系统安装docker 1yum install docker 安装gitlab-ce和端口配置 123456789sudo docker">
<meta property="og:type" content="article">
<meta property="og:title" content="gitlab-cicd">
<meta property="og:url" content="https://mo_zi_hao.gitee.io/blog/posts/23125/index.html">
<meta property="og:site_name" content="mozihao">
<meta property="og:description" content="使用docker + gitlab自动化部署前端项目安装docker和gitlab-ce及配置 运行linux服务器，终端打开 1ssh root@ + 公网ip  公网ip：阿里云云服务器–&gt;实例与镜像–&gt;实例（实例详情中的公网ip）  linux系统安装docker 1yum install docker 安装gitlab-ce和端口配置 123456789sudo docker">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/mo_zi_hao/picsBed/raw/master/image/745.jpg">
<meta property="article:published_time" content="2021-12-20T14:00:59.661Z">
<meta property="article:modified_time" content="2023-02-18T02:48:35.770Z">
<meta property="article:author" content="mozihao">
<meta property="article:tag" content="mozihao github">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/mo_zi_hao/picsBed/raw/master/image/745.jpg"><link rel="shortcut icon" href="/blog/img/favicon.png"><link rel="canonical" href="https://mo_zi_hao.gitee.io/blog/posts/23125/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/blog/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/blog/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-02-18 10:48:35'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    })(window)</script><link rel="stylesheet" type="text/css" href="./css/iconfont.css" media="all"><meta name="generator" content="Hexo 5.4.2"><link rel="alternate" href="/blog/atom.xml" title="mozihao" type="application/atom+xml">
</head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src="https://gitee.com/mo_zi_hao/picsBed/raw/master/image/%E6%B5%B7%E8%B4%BC008.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">24</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">16</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">11</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 前端知识思维导图</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://gitee.com/mo_zi_hao/picsBed/raw/master/image/745.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/blog/">mozihao</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 前端知识思维导图</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">gitlab-cicd</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-12-20T14:00:59.661Z" title="发表于 2021-12-20 22:00:59">2021-12-20</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-02-18T02:48:35.770Z" title="更新于 2023-02-18 10:48:35">2023-02-18</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/Git/">Git</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.6k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>9分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="gitlab-cicd"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="使用docker-gitlab自动化部署前端项目"><a href="#使用docker-gitlab自动化部署前端项目" class="headerlink" title="使用docker + gitlab自动化部署前端项目"></a>使用docker + gitlab自动化部署前端项目</h1><h3 id="安装docker和gitlab-ce及配置"><a href="#安装docker和gitlab-ce及配置" class="headerlink" title="安装docker和gitlab-ce及配置"></a>安装docker和gitlab-ce及配置</h3><ol>
<li><p>运行linux服务器，终端打开</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ssh root@ + 公网ip</span><br></pre></td></tr></table></figure>

<p>公网ip：阿里云云服务器–&gt;实例与镜像–&gt;实例（实例详情中的公网ip）</p>
</li>
<li><p>linux系统安装docker</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">yum install docker</span><br></pre></td></tr></table></figure></li>
<li><p>安装gitlab-ce和端口配置</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">sudo docker run --detach \</span><br><span class="line">  --hostname gitlab.mczaiyun.top \</span><br><span class="line">  --publish 443:443 --publish 80:80 --publish 222:22 \</span><br><span class="line">  --name gitlab \</span><br><span class="line">  --restart always \</span><br><span class="line">  --volume /srv/gitlab/config:/etc/gitlab \</span><br><span class="line">  --volume /srv/gitlab/logs:/var/log/gitlab \</span><br><span class="line">  --volume /srv/gitlab/data:/var/opt/gitlab \</span><br><span class="line">  gitlab/gitlab-ce:latest</span><br></pre></td></tr></table></figure>

<p>hostname  域名 或 ip</p>
<p>publish 端口映射</p>
<p>restart 重启方式</p>
<p>gitlab/gitlab-ce:latest  镜像名称</p>
<p>volume 目录挂载</p>
</li>
<li><p>```<br>//查看运行的容器<br>docker container ls -a<br>//查看gitlab的启动日志<br>docker logs -f gitlab</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">5. 此时只能使用ip进行访问gitlab</span><br><span class="line"></span><br><span class="line">   要使用域名访问，我们需要在阿里云进行DNS云解析</span><br><span class="line"></span><br><span class="line">   目录：解析设置 -&gt; 添加记录 -&gt;</span><br><span class="line"></span><br><span class="line">   主机记录：填写gitlab；</span><br><span class="line"></span><br><span class="line">   解析记录：填写服务器ip</span><br><span class="line"></span><br><span class="line">   ![image-20211222215914111](/Users/mozihao/Desktop/未命名文件夹/image-20211222215914111.png)</span><br><span class="line"></span><br><span class="line">### gitlab-cicd配置及搭建</span><br><span class="line"></span><br><span class="line">#### 安装gitlab-runner</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>sudo docker run -d –name gitlab-runner –restart always \</p>
</li>
</ol>
<p>  -v /srv/gitlab-runner/config:/etc/gitlab-runner <br>  -v /var/run/docker.sock:/var/run/docker.sock <br>  gitlab/gitlab-runner:latest</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"></span><br></pre></td></tr></table></figure>
<p>// 查看已安装的容器<br>docker sp -a</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">**使gitlab-ce和gitlab-runner之间产生联系--注册gitlab-runnner，通过token使两者之间产生联系，运行下面代码修改下面的配置，注册runner和配置runner**</span><br><span class="line"></span><br><span class="line">（在gitlab里面的runners，那里有一个token和你的gitlab地址）</span><br><span class="line"></span><br><span class="line">![image-20211222235508591](/Users/mozihao/Desktop/未命名文件夹/image-20211222235508591.png)</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>docker run –rm -v /srv/gitlab-runner/config:/etc/gitlab-runner gitlab/gitlab-runner register <br>  –non-interactive <br>  –executor “docker” <br>  –docker-image alpine:latest <br>  –url “这里填写gitlab地址” <br>  –registration-token “这里填写token” <br>  –description “first-register-runner（这里是runner的描述）” <br>  –tag-list “test-cicd,dockercicd（这里是runner标签，用来指定流水线在哪个状态下运行）” <br>  –run-untagged=”true” <br>  –locked=”false” <br>  –access-level=”not_protected”</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">**修改以上命令，在linux终端执行**</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">#### 编写gitlab-ci.yml文件</span><br><span class="line"></span><br><span class="line">我们能想到：我们手动打包部署的流程</span><br><span class="line"></span><br><span class="line">1.终端执行npm install 安装依赖</span><br><span class="line"></span><br><span class="line">2.终端执行npm run build 打包</span><br><span class="line"></span><br><span class="line">3.将build包部署到服务器上</span><br><span class="line"></span><br><span class="line">所以，我们ci/cd流水线有 三个阶段：`安装依赖 -&gt; 打包 -&gt; 部署`</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">**首先我们先在gitlab创建一个前端项目（这里自行创建，我就不再这里展开）**</span><br><span class="line"></span><br><span class="line">然后我们在gitlab里进入到这个项目的详情，我们可以看到CI/CD configuration，点击这里我们可以编辑这个项目的gitlab-ci.yml文件（当然你也可以将项目拉下来，在根目录新建gitlab-ci.yml文件去编写，编写完后提交到远程）</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">##### **常用关键词**：</span><br><span class="line"></span><br><span class="line">`image`: 指定一个基础Docker镜像作为基础运行环境，常用到的镜像有node、java、python、docker等</span><br><span class="line"></span><br><span class="line">`stage`: 流水线任务的某个阶段</span><br><span class="line"></span><br><span class="line">`tags`：指定Runner，tags的取值范围是在该项目可见的runner tags中</span><br><span class="line"></span><br><span class="line">`script`：shell脚本的执行</span><br><span class="line"></span><br><span class="line">`retry`:  例 retry: 1    表示如果任务失败了重试1次（限制范围0-2，最多运行三次），也可以使用when关键词，遇到某些失败才重试，具体理解更多看官方文档</span><br><span class="line"></span><br><span class="line">`when`: 定义了job什么时候执行，可以是on_success（所有任务执行成功后）、on_failure（当至少一个任务失败后）、always（执行作业，而不考虑作业在早期阶段的状态）、manual（手动执行任务）、delayed（延时执行任务）</span><br><span class="line"></span><br><span class="line">`only`：限定某些分支某些tag能执行这个阶段的任务</span><br><span class="line"></span><br><span class="line">`except`：排除某些分支某些tag</span><br><span class="line"></span><br><span class="line">`cache`：缓存是将当前工作环境目录中的一些文件，在一些文件夹存储起来，用于在各个任务初始化的时候恢复</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">##### 首先我们定义三个阶段</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>stages:</p>
<ul>
<li>install    #安装依赖</li>
<li>build    #打包</li>
<li>deploy    #部署<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">但是我们需要执行install需要node环境呀，此时需要使用image关键词， 指定一个基础Docker镜像作为基础运行环境，这里我用的12.X的版本的node，其中alpine是表示体积小的镜像，你也可以使用新版node:latest</span><br><span class="line"></span><br></pre></td></tr></table></figure>
image: node:12-alpine</li>
</ul>
<p>stages:</p>
<ul>
<li>install    #安装依赖</li>
<li>build    #打包</li>
<li>deploy    #部署<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">这里我们写一下这三个阶段，他们都有一个任务名称分别为job_intall，job_build，job_deploy（这些任务名称可自行定义名字，没有规定）</span><br><span class="line"></span><br><span class="line">##### 第一个阶段 install</span><br><span class="line"></span><br></pre></td></tr></table></figure>
image: node:12-alpine</li>
</ul>
<p>stages:</p>
<ul>
<li>install    #安装依赖</li>
<li>build    #打包</li>
<li>deploy    #部署</li>
</ul>
<p>#install阶段<br>job_intall:<br> stage: install    #任务内的阶段，对应上面定义的三个阶段中的install<br> tags:<br>     - test-cicd #这里为我们要执行对应这个test-cicd标签的runner<br> script:</p>
<ul>
<li>yarn install    #shell执行命令安装依赖</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">那么我们执行的命令是在终端执行的，那我们在gitlab-ci.yml文件怎么执行这些命令呢，此时使用script关键词，shell脚本的执行</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">##### 第二个阶段 build</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>#build阶段<br>job_build:<br>    stage: build #任务内的阶段，对应上面定义的三个阶段中的build<br>    tags:<br>     - test-cicd #这里为我们要执行对应这个test-cicd标签的runner<br>    script:<br>     - npm run build #shell执行命令进行打包</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">我们在执行第一个阶段的时候会出现我们的node_modules包被清理的情况，导致我们的第二个阶段的npm run build执行会发生错误，所以我们需要使用缓存cache将我们的node_modules缓存起来</span><br><span class="line"></span><br><span class="line">![image-20211225155513067](/Users/mozihao/Desktop/未命名文件夹/image-20211225155513067.png)</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>image: node:12-alpine</p>
<p>stages:</p>
<ul>
<li>install    #安装依赖</li>
<li>build    #打包</li>
<li>deploy    #部署</li>
</ul>
<p>cache:<br>  key: node-modules-cache #缓存需要设置一个hash否则会验证失败，这里需要指定一个key代表着版本的唯一标识<br>  paths:<br>    - node_modules #这里的paths为文件路径，这里也可以缓存多个文件或者目录，需要指定多个直接换行 - 指定文件/目录</p>
<p>#install阶段<br>job_intall:<br> stage: install    #任务内的阶段，对应上面定义的三个阶段中的install<br> tags: </p>
<ul>
<li>test-cicd #这里为我们要执行对应这个test-cicd标签的runner<br>script:</li>
<li>yarn install    #shell执行命令安装依赖</li>
</ul>
<p>#build阶段<br>job_build:<br>    stage: build #任务内的阶段，对应上面定义的三个阶段中的build<br>    tags:<br>     - test-cicd #这里为我们要执行对应这个test-cicd标签的runner<br>    script:<br>     - npm run build #shell执行命令进行打包</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">##### 第三个阶段 deploy</span><br><span class="line"></span><br><span class="line">这个阶段需要使用docker命令去打包镜像，然后在对应的容器里面运行，所以这里需要先引入docker镜像，然后是用docker build命令打包镜像（注意：这个打包命令是需要配合dockerfile文件，下面会进行编写），然后使用docker run运行指定的容器和此前docker build的docker镜像</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>image: node:12-alpine</p>
<p>stages:</p>
<ul>
<li>install    #安装依赖</li>
<li>build    #打包</li>
<li>deploy    #部署</li>
</ul>
<p>cache:<br>  key: node-modules-cache #缓存需要设置一个hash否则会验证失败，这里需要指定一个key代表着版本的唯一标识<br>  paths:<br>    - node_modules #这里的paths为文件路径，这里也可以缓存多个文件或者目录，需要指定多个直接换行 - 指定文件/目录</p>
<p>#install阶段<br>job_intall:<br> stage: install    #任务内的阶段，对应上面定义的三个阶段中的install<br> tags: </p>
<ul>
<li>test-cicd #这里为我们要执行对应这个test-cicd标签的runner<br>script:</li>
<li>yarn install    #shell执行命令安装依赖</li>
</ul>
<p>#build阶段<br>job_build:<br>    stage: build #任务内的阶段，对应上面定义的三个阶段中的build<br>    tags:<br>     - test-cicd #这里为我们要执行对应这个test-cicd标签的runner<br>    script:<br>     - npm run build #shell执行命令进行打包</p>
<p>#deploy阶段<br>job_deploy:<br>    image: docker #因为下面需要用到docker命令，需要docker的运行环境，这里需要引入docker镜像<br>    stage: deploy #任务内的阶段，对应上面定义的三个阶段中的deploy<br>    tags:<br>     - test-cicd #这里为我们要执行对应这个test-cicd标签的runner<br>    script:<br>     - docker build -t appimages . #执行过docker的打包命令，打包一个名为appimage的镜像（注意 . 不能省略…语法），但这个命令能成功运行是需要我们编写一个dockerfile文件的，下面会讲<br>     - if [ $(docker ps -aq –filter name=app-container) ]; then docker rm -f app-container;fi #if是是判断语句，里面filter的那个语法是查找docker里面是否存在一个名为app-container的容器，then是如果存在就会执行删除命令rm -f删除app-container这个容器<br>     - docker run -d -p 8080:80 –name app-container appimages #重新运行新的容器指定8080端口映射80端口，并指定我们上面打包好的appimages镜像</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">在执行docker build的时候，如果没有配置docker的目录卷，可能会发生一下错误</span><br><span class="line"></span><br><span class="line">![image-20211225222908599](/Users/mozihao/Desktop/未命名文件夹/image-20211225222908599.png)</span><br><span class="line"></span><br><span class="line"> 目录卷在我们的runner配置文件里面配置，在linux终端执行一下命令，打开runner的配置文件</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>vim /srv/gitlab-runner/config/config.toml</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">找到我们对应的runner之后，在volumes添加下面这行文件目录的映射关系（默认只有&quot;/cache&quot;）</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>“/usr/bin/docker:/usr/bin/docker”, “/var/run/docker.sock:/var/run/docker.sock”</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">![image-20211225223755047](/Users/mozihao/Desktop/未命名文件夹/image-20211225223755047.png)</span><br><span class="line"></span><br><span class="line">#### 编写dockerfile文件</span><br><span class="line"></span><br><span class="line">在项目的根目录（就是和gitlab-ci.yml的同级目录）新建Dockerfile文件，下面代码为Dockerfile的配置</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>FROM node:12-alpine as builder<br>WORKDIR /app<br>COPY package.json .<br>RUN npm install –registry=<a target="_blank" rel="noopener" href="http://registry.npm.taobao.org/">http://registry.npm.taobao.org</a><br>COPY . .<br>RUN npm run build</p>
<p>FROM nginx:latest<br>COPY –from=builder /app/dist /usr/share/nginx/html</p>
<pre><code>
注释：

1. 代码的第一句为使用node的12.X版本最小体积的镜像用作打包（下面的npm run build和npm install 需要node环境）
2. 第二段为在 当前文件的/app文件夹
3. 将package.json 复制到 当前文件夹（/app）
4. 执行npm install 安装依赖
5. 将当前文件夹的所有文件复制一遍
6. 执行npm run build 进行打包
7. 使用nginx的最小版本的镜像
8. 将打包好的app文件夹下的dist目录 复制 到nginx的目录/usr/share/nginx/html里面



#### ⭐️cicd基本完成

到这里一个简单的cicd已经完成了，当cicd运行好之后，直接使用公网ip:8080可打开我们的页面，这里的8080，是因为我们上面docker run -d -p 8080:80指定的就是8080端口
</code></pre>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">mozihao</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://mo_zi_hao.gitee.io/blog/posts/23125/">https://mo_zi_hao.gitee.io/blog/posts/23125/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://mo_zi_hao.gitee.io/blog" target="_blank">mozihao</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="https://gitee.com/mo_zi_hao/picsBed/raw/master/image/745.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/blog/posts/36549/"><img class="prev-cover" src="https://gitee.com/mo_zi_hao/picsBed/raw/master/image/%E6%B5%B7%E8%B4%BC4.jpg" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">编写可维护的JavaScript (代码习惯)</div></div></a></div><div class="next-post pull-right"><a href="/blog/posts/449/"><img class="next-cover" src="https://gitee.com/mo_zi_hao/picsBed/raw/master/image/26&amp;gp=0.jpg" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">前端js基础</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" src="https://gitee.com/mo_zi_hao/picsBed/raw/master/image/%E6%B5%B7%E8%B4%BC008.jpg" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">mozihao</div><div class="author-info__description">if you risk nothing,then you risk anthing</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">24</div></a></div><div class="card-info-data-item is-center"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">16</div></a></div><div class="card-info-data-item is-center"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">11</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/mo_zi_hao"><i class="iconfont icon-gitee-fill-round"></i><span>我的Gitee</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitee.com/mo_zi_hao" target="_blank" title="Gitee"><i class="fab iconfont icon-gitee-fill-round"></i></a><a class="social-icon" href="https://github.com/mmCrazy" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="https://blog.csdn.net/xiaomohhh?spm=1001.2101.3001.5343" target="_blank" title="CSDN"><i class="fab iconfont icon-csdn"></i></a><a class="social-icon" href="https://gitee.com/mo_zi_hao/picsBed/raw/master/image/qrcode_for_gh_d35478eda980_430.jpg" target="_blank" title="公众号"><i class="fab iconfont icon-weixingongzhonghao"></i></a><a class="social-icon" href="mailto:747304031@qq.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">如文章中有哪些错漏，欢迎各位前端的大佬与我交流并指正，谢谢!!</br>邮箱：747304031@qq.com</br>公众号：一起写前端bug</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8docker-gitlab%E8%87%AA%E5%8A%A8%E5%8C%96%E9%83%A8%E7%BD%B2%E5%89%8D%E7%AB%AF%E9%A1%B9%E7%9B%AE"><span class="toc-number">1.</span> <span class="toc-text">使用docker + gitlab自动化部署前端项目</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%89%E8%A3%85docker%E5%92%8Cgitlab-ce%E5%8F%8A%E9%85%8D%E7%BD%AE"><span class="toc-number">1.0.1.</span> <span class="toc-text">安装docker和gitlab-ce及配置</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/blog/posts/1/" title="无题"><img src="https://gitee.com/mo_zi_hao/picsBed/raw/master/image/%E6%B5%B7%E8%B4%BC4.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="无题"/></a><div class="content"><a class="title" href="/blog/posts/1/" title="无题">无题</a><time datetime="2022-06-05T05:20:17.974Z" title="发表于 2022-06-05 13:20:17">2022-06-05</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/posts/36549/" title="编写可维护的JavaScript (代码习惯)"><img src="https://gitee.com/mo_zi_hao/picsBed/raw/master/image/%E6%B5%B7%E8%B4%BC4.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="编写可维护的JavaScript (代码习惯)"/></a><div class="content"><a class="title" href="/blog/posts/36549/" title="编写可维护的JavaScript (代码习惯)">编写可维护的JavaScript (代码习惯)</a><time datetime="2022-03-19T03:12:42.624Z" title="发表于 2022-03-19 11:12:42">2022-03-19</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/posts/23125/" title="gitlab-cicd"><img src="https://gitee.com/mo_zi_hao/picsBed/raw/master/image/745.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="gitlab-cicd"/></a><div class="content"><a class="title" href="/blog/posts/23125/" title="gitlab-cicd">gitlab-cicd</a><time datetime="2021-12-20T14:00:59.661Z" title="发表于 2021-12-20 22:00:59">2021-12-20</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/posts/449/" title="前端js基础"><img src="https://gitee.com/mo_zi_hao/picsBed/raw/master/image/26&amp;gp=0.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="前端js基础"/></a><div class="content"><a class="title" href="/blog/posts/449/" title="前端js基础">前端js基础</a><time datetime="2021-08-29T15:22:14.600Z" title="发表于 2021-08-29 23:22:14">2021-08-29</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/posts/35506/" title="微信小程序"><img src="https://gitee.com/mo_zi_hao/picsBed/raw/master/image/1234.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="微信小程序"/></a><div class="content"><a class="title" href="/blog/posts/35506/" title="微信小程序">微信小程序</a><time datetime="2021-08-29T15:22:14.600Z" title="发表于 2021-08-29 23:22:14">2021-08-29</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By mozihao</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/blog/js/utils.js"></script><script src="/blog/js/main.js"></script><script src="/blog/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/blog/js/search/local-search.js"></script><div class="js-pjax"></div><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-heart.min.js" async="async" mobile="false"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/gh/metowolf/MetingJS@1.2/dist/Meting.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>